package com.example.music_liwei.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music_liwei.R;
import com.example.music_liwei.bean.ResponseData;

import java.util.List;

public class MusicListAdapter extends RecyclerView.Adapter<MusicListAdapter.ViewHolder> {

    private List<ResponseData.MusicInfo> musicInfoList;
    private OnItemRemoveListener onItemRemoveListener;

    public MusicListAdapter(List<ResponseData.MusicInfo> musicInfoList, OnItemRemoveListener onItemRemoveListener) {
        this.musicInfoList = musicInfoList;
        this.onItemRemoveListener = onItemRemoveListener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_music, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ResponseData.MusicInfo musicInfo = musicInfoList.get(position);
        holder.tvMusicName.setText(musicInfo.getMusicName());
        holder.tvAuthor.setText(musicInfo.getAuthor());

        holder.ivDelete.setOnClickListener(v -> {
            if (onItemRemoveListener != null) {
                onItemRemoveListener.onItemRemove(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return musicInfoList.size();
    }

    public void updateMusicList(List<ResponseData.MusicInfo> newMusicInfoList) {
        this.musicInfoList = newMusicInfoList;
        notifyDataSetChanged();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvMusicName, tvAuthor;
        ImageView ivDelete;

        ViewHolder(View itemView) {
            super(itemView);
            tvMusicName = itemView.findViewById(R.id.tv_music_name);
            tvAuthor = itemView.findViewById(R.id.tv_author);
            ivDelete = itemView.findViewById(R.id.iv_delete);
        }
    }

    public interface OnItemRemoveListener {
        void onItemRemove(int position);
    }
}
